"""
项目主入口文件
使用FastAPI将当前项目接口化，实现Google AI模型的OpenAI兼容API
"""
import os
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
import time

from py_files.config import FASTAPI_BASE_URL, INPUT_DIR, OUTPUT_DIR
from py_files.router_model import router as model_router
from py_files.router_openai_compat import router as openai_compat_router

# 导入模型配置
from py_files.config import get_all_models, select_model

# 创建FastAPI应用
app = FastAPI(
    title="Google大模型API兼容接口",
    description="提供Google大模型的OpenAI兼容API接口",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json",
)

# 添加CORS中间件，确保支持Authorization头
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*", "Authorization", "x-api-key"],  # 明确允许认证头
)

# 包含路由 - 移除chat路由，仅保留model路由
app.include_router(model_router, prefix=f"{FASTAPI_BASE_URL}")

# 添加OpenAI兼容格式的路由（使用/v1前缀）
app.include_router(openai_compat_router, prefix="/v1")

# 根路由
@app.get("/", response_class=HTMLResponse)
async def root():
    html_content = """
    <html>
        <head>
            <title>Google大模型API兼容接口</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    max-width: 800px;
                    margin: 0 auto;
                    padding: 20px;
                    line-height: 1.6;
                }
                h1 {
                    color: #333;
                    border-bottom: 1px solid #eee;
                    padding-bottom: 10px;
                }
                h2 {
                    color: #444;
                    margin-top: 20px;
                }
                ul {
                    margin-bottom: 20px;
                }
                a {
                    color: #0066cc;
                    text-decoration: none;
                }
                a:hover {
                    text-decoration: underline;
                }
                .api-section {
                    background-color: #f9f9f9;
                    padding: 15px;
                    border-radius: 5px;
                    margin-bottom: 20px;
                }
            </style>
        </head>
        <body>
            <h1>Google大模型API兼容接口</h1>
            <p>提供Google大模型的OpenAI兼容API接口。</p>
            
            <div class="api-section">
                <h2>API文档</h2>
                <ul>
                    <li><a href="/docs">Swagger UI 文档</a></li>
                    <li><a href="/redoc">ReDoc 文档</a></li>
                </ul>
            </div>
            
            <div class="api-section">
                <h2>主要API端点</h2>
                <ul>
                    <li><a href="/api/googleOpenaiCompat/health">健康检查</a></li>
                    <li><a href="/api/googleOpenaiCompat/model/list">模型列表</a></li>
                    <li><a href="/api/googleOpenaiCompat/chat/models">聊天模型列表</a></li>
                    <li><a href="/models">所有支持的模型与选择的模型</a></li>
                </ul>
            </div>
            
            <div class="api-section">
                <h2>OpenAI兼容API（标准格式）</h2>
                <ul>
                    <li><a href="/v1/models">模型列表 (/v1/models)</a></li>
                    <li><a href="/v1/engines">引擎列表 (/v1/engines) - 旧版兼容</a></li>
                    <li>POST /v1/chat/completions - 聊天补全API</li>
                </ul>
            </div>
            
            <p>© 2024 Google大模型API兼容接口</p>
        </body>
    </html>
    """
    return HTMLResponse(content=html_content)

# 添加模型信息路由
@app.get("/models")
async def get_models():
    """
    返回支持的模型和当前选择的模型
    """
    return {
        "models": get_all_models(),
        "select_model": select_model
    }

# 健康检查路由
@app.get(f"{FASTAPI_BASE_URL}/health")
async def health_check():
    """
    健康检查API
    """
    # 检查必要目录是否存在，不存在则创建
    for directory in [INPUT_DIR, OUTPUT_DIR]:
        if not os.path.exists(directory):
            os.makedirs(directory)
    
    return {
        "status": "OK",
        "api_version": "1.0.0",
        "FASTAPI_BASE_URL": FASTAPI_BASE_URL,
        "directories": {
            "input_dir": INPUT_DIR,
            "output_dir": OUTPUT_DIR
        }
    }

# 错误处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={"detail": str(exc)},
    )

# 添加新的路由
@app.get("/ping")
async def ping():
    """
    简单的ping测试，不需要任何认证
    """
    return {"ping": "pong", "time": time.time()}

# 入口函数
def main():
    """主程序入口"""
    # 确保必要目录存在
    for directory in [INPUT_DIR, OUTPUT_DIR]:
        if not os.path.exists(directory):
            os.makedirs(directory)

    # 明确指定host为0.0.0.0，确保所有网络接口可访问
    uvicorn.run("main:app", host="0.0.0.0", port=8006, reload=True, log_level="debug")

if __name__ == "__main__":
    main() 